import json
import os
from lib.esign.helpFile import HttpHelper, Message
# from colorama import init, Fore
# init(autoreset=True)  # 重置序列结束时关闭颜色变化每一个打印,然后init(autoreset = True)将自动化
#  创建个人账户
from lib.esign.helpFile.FileMD5 import content_encoding
import traceback
import logging
app_logger = logging.getLogger("student")


def addPerson(thirdPartyUserId, name, idNo, idType, mobile):
    """
    创建个人账户开始
    :param thirdPartyUserId:
    :param name:
    :param idNo:
    :param idType:
    :param mobile:
    :return:
    """
    try:
        # 组装参数
        reqBodyData = {"thirdPartyUserId": thirdPartyUserId, "name": name, "idNo": idNo, "idType": idType,
                       "mobile": mobile}
        # 将数组转成json字符串
        reqBodyData = json.dumps(reqBodyData)
        print('reqBodyData=', reqBodyData.encode('utf-8').decode('unicode_escape'))
        url = "/v1/accounts/createByThirdPartyUserId"
        # 发送post请求进行项目初始化
        Result = HttpHelper.HttpHelper.doPOST(url, reqBodyData)
        personStr = json.loads(Result)
        app_logger.error(Result)
        #accountid = personStr['data']['accountId']
        return personStr
    except:
        err = traceback.format_exc()
        app_logger.error(err)
        return False


def addOrgaccountid(thirdPartyUserId, name, idNumber, idType, orgLegalIdNumber, orgLegalName):
    """
    #创建企业账户
    :param thirdPartyUserId:
    :param creator:
    :param name:
    :param idNumber:
    :param idType:
    :param orgLegalIdNumber:
    :param orgLegalName:
    :return:
    """
    try:
        # 组装参数
        reqBodyData = {"thirdPartyUserId": thirdPartyUserId, "name": name, "idNumber": idNumber,
                       "idType": idType, "orgLegalIdNumber": orgLegalIdNumber, "orgLegalName": orgLegalName}
        # 将数组转成json字符串
        reqBodyData=json.dumps(reqBodyData)
        print('reqBodyData=', reqBodyData.encode('utf-8').decode('unicode_escape'))
        #请求地址
        url="/v1/organizations/createByThirdPartyUserId"
        # 发送post请求进行项目初始化
        Result =HttpHelper.HttpHelper.doPOST(url, reqBodyData)
        print("创建企业账户结果集：" + Result)
        personStr = json.loads(Result)
        # accountid = personStr['data']['orgId']
        return personStr
    except:
        err = traceback.format_exc()
        app_logger.error(err)
        return False


def uploadFile(file, true=None):
    """
    #上传方式创建文件
    :param file:
    :param true:
    :return:
    """
    try:
        print("---获取文件fileid以及uploadUrl开始---")
        # 组装参数
        contentMd5 = content_encoding(file)
        fileName = os.path.basename(file)
        fileSize = os.path.getsize(file)
        contentType = 'application/octet-stream'
        convert2Pdf = true
        reqBodyData = {"contentMd5": contentMd5, "contentType": contentType, "convert2Pdf": convert2Pdf,
                       "fileName": fileName, "fileSize": fileSize}
        # 将数组转成json字符串
        reqBodyData=json.dumps(reqBodyData)
        # print('reqBodyData=', reqBodyData.encode('utf-8').decode('unicode_escape'))
        #请求地址
        url = "/v1/files/getUploadUrl"
        # 发送post请求进行项目初始化
        Result = HttpHelper.HttpHelper.doPOST(url, reqBodyData)
        personStr = json.loads(Result)
        uploadUrl = personStr['data']['uploadUrl']
        #  上传文件结果集
        Result1 = HttpHelper.HttpHelper.doPUT(uploadUrl, file, contentType, contentMd5)
        #personStr1 = json.loads(Result1)
        #code = personStr1['data']['orgId']
        # print("accountid："+accountid)
        return personStr
    except:
        err = traceback.format_exc()
        app_logger.error(err)
        return False


def createFlowOneStep(fileid, personAccountid, Orgaccountid, file, type, posX=300.00, posY=300.00, platform=0, saccount=''):
    """
    #一步发起签署开始
    :param fileid:
    :param personAccountid:
    :param Orgaccountid:
    :param file:
    :return:
    """
    try:
        redirectUrl = 'ysdx://momself/signBack'
        fileName=os.path.basename(file)
        #组装待签署文件
        docs = [{"fileId": fileid, "fileName": fileName}]
        #组装签署基本信息
        notifyConfig = {"noticeType": "1", "noticeDeveloperUrl": "http://prod.momself.cn/api/esign/signflows/notify"}
        signConfig = {"signPlatform": "1", "redirectDelayTime": 0}
        flowConfigInfo = {"notifyConfig": notifyConfig, "signConfig": signConfig}
        flowInfo = {"businessScene": "合同签订", "autoArchive": True, "autoInitiate": True, "flowConfigInfo": flowConfigInfo}
        #组装签署人信息
        signerAccount = {"signerAccount": personAccountid}
        #签署区位置
        posBean1 = {"posPage": "1", "posX": posX, "posY": posY}
        posBean2 = {"posPage": "1", "posX": 100.00, "posY": 100.00}
        signfields1 = [{"fileId": fileid, "sealType": '', "signType": "1", "assignedPosbean": False, "actorIndentityType": 0,
                        "posBean": posBean1}]
        signfields2 = [{"actorIndentityType": 2, "fileId": fileid, "sealType": "1", "signType": 0, "posBean": posBean2}]

        signfields3 = [{"autoExecute": True, "actorIndentityType": 2, "fileId": fileid, "sealType": "1",
                        "signType": "1", "posBean": posBean2}]
        #个人代企业
        signers1 = {"platformSign": False, "signerAccount": signerAccount, "signfields": signfields1}
        #平台方自动签署
        signers2 = {"platformSign": False, "signfields": signfields2, "signerAccount": {"authorizedAccount": Orgaccountid,
                                                                                        "signerAccount": saccount}}
        signers3 = {"platformSign": True, "signfields": signfields3}
        if type == 1:  # 平台自动签署
            signers = [signers1, signers3]
        else:
            signers = [signers1, signers2]
        reqBodyData = {"docs": docs, "flowInfo": flowInfo, "signers": signers}
        reqBodyData = json.dumps(reqBodyData)
        url = "/api/v3/signflows/createFlowOneStep"
        Result = HttpHelper.HttpHelper.doPOST(url, reqBodyData)
        app_logger.error("这是一步发起电签返回")
        app_logger.error(Result)
        personStr = json.loads(Result)
        return personStr
    except:
        err = traceback.format_exc()
        app_logger.error(err)
        return False


def getExecuteUrl(flowId, signerAccount, authorizedAccount='', platform=0, types=0):
    """
    获取签署地址
    :param flowId:
    :param accountId:
    :param organizeId:
    :return:
    """
    try:
        url = "/v3/signflows/{}/executeUrl".format(flowId)
        reqBodyData = {}
        if types == 1:  # 获取个人签署
            appScheme = 'ysdx://momself/OpenAccountBack'
            reqBodyData = {"signerAccount": signerAccount, "appScheme": appScheme, "redirectUrl": appScheme}
        if types == 2:
            appScheme = 'ysdx://momself/signBack'
            reqBodyData = {"signerAccount": signerAccount, "appScheme": appScheme, "authorizedAccount": authorizedAccount,
                           "redirectUrl": appScheme}
        app_logger.error(reqBodyData)
        reqBodyData = json.dumps(reqBodyData)
        res = HttpHelper.HttpHelper.doGet(url, reqBodyData)
        app_logger.error("这是获取签署地址的返回")
        app_logger.error(res)
        personStr = json.loads(res)
        return personStr
    except:
        err = traceback.format_exc()
        app_logger.error(err)
        return False


def setSealsOfficialtemplate(orgId, color, type, alias, height=159, width=159, htext='', qtext=''):
    """
    设置印章
    :param orgId:
    :param color:
    :param type:
    :return:
    """
    try:
        url = "/v1/organizations/{orgId}/seals/officialtemplate"
        params = {'color': color, 'type': type, 'height': height, 'width': width, 'htext': htext, 'qtext': qtext,
                  'alias': alias}
        res = HttpHelper.HttpHelper.doPOST(url, params)
        personStr = json.loads(res)
        return personStr
    except:
        err = traceback.format_exc()
        app_logger.error(err)
        return False


def oauth2(redirectUrl, notifyUrl, bizType, state=None, account='', platform=0, level=0, name=None):
    """
    实名认证
    :param account:
    :param redirectUrl:
    :param bizType:
    :return:
    """
    try:
        redirectUrl = 'ysdx://momself/realBack'
        if level == 3:
            redirectUrl = 'ysdx://momself/OpenAccountBack'
        reqBodyData = {"account": account, "redirectUrl": redirectUrl, "bizType": bizType, "state": state,
                       "notifyUrl": notifyUrl, "appId": HttpHelper.appId,
                       "authConfigParam": {"authType": "PSN_TELECOM_AUTHCODE", "forceRealname": True,
                                           "availableAuthTypes": ["PSN_TELECOM_AUTHCODE",
                                                                  "PSN_FACEAUTH_BYURL",
                                                                  "PSN_BANK4_AUTHCODE"],
                                           "indivEditableInfo": ["name", "certNo"], "showResultPage": True}}
        if str(bizType) == 'combination':
            redirectUrl = 'ysdx://momself/OpenAccountBack'
            authConfigParam = {"availableAuthTypes": ["ORG_BANK_TRANSFER", "ORG_LEGAL_AUTHORIZE", "ORG_ZM_AUTHORIZE",
                                                      "LEGAL_REP_AUTH"],
                               "indivEditableInfo": ["name", "certNo"], "orgEditableInfo": ["name"],
                               "showResultPage": True, "forceRealname": True}
            authSubject = {"organizationType": 1, "name": name}
            reqBodyData = {"responseType": "code", "scope": "get_user_info,op_organ_admin", "account": account,
                           "redirectUrl": redirectUrl, "bizType": bizType, "state": state, "notifyUrl": notifyUrl,
                           "appId": HttpHelper.appId, "authConfigParam": authConfigParam, "authSubject": authSubject}
        reqBodyData = json.dumps(reqBodyData)
        url = "/v3/oauth2/index"
        app_logger.error(reqBodyData)
        Result = HttpHelper.HttpHelper.doPOST(url, reqBodyData)
        personStr = json.loads(Result)
        return personStr
    except:
        err = traceback.format_exc()
        app_logger.error(err)
        return False


def authorizerInfo(mobile):
    """
    查询个人实名状态
    :param mobile:
    :return:
    """
    reqBodyData = {"mobile": mobile}
    url = "/v2/open/accounts/realNameInfo"
    reqBodyData = json.dumps(reqBodyData)
    Result = HttpHelper.HttpHelper.doPOST(url, reqBodyData)
    personStr = json.loads(Result)
    return personStr


def organizations(name):
    """
    查询组织机构实名状态
    :param name:
    :return:
    """
    reqBodyData = {"name": name}
    url = "/v2/open/organizations/realNameInfo"
    reqBodyData = json.dumps(reqBodyData)
    Result = HttpHelper.HttpHelper.doPOST(url, reqBodyData)
    personStr = json.loads(Result)
    return personStr


def documents(flowId):
    """
    下载合同
    :param flowId:
    :return:
    """
    reqBodyData = {}
    url = "/v1/signflows/{}/documents".format(flowId)
    reqBodyData = json.dumps(reqBodyData)
    Result = HttpHelper.HttpHelper.doGet(url, reqBodyData)
    personStr = json.loads(Result)
    return personStr


def downloadFile(fileId):
    """
    下载合同模板文件
    :param fileId:
    :return:
    """
    reqBodyData = {}
    url = "/v1/files/{}".format(fileId)
    reqBodyData = json.dumps(reqBodyData)
    Result = HttpHelper.HttpHelper.doGet(url, reqBodyData)
    personStr = json.loads(Result)
    return personStr